<template>
  <div v-if="isShowTree">
    <el-input
      style="margin-bottom: 20px"
      :disabled="true"
      size="mini"
      :value="role.roleName"
    ></el-input>
    <el-tree
      :default-checked-keys="isSelectData"
      :data="data"
      show-checkbox
      default-expand-all
      node-key="id"
      ref="tree"
      :props="defaultProps"
      @check-change="nodeSelect"
    >
    </el-tree>
    <el-button type="primary" size="mini" @click="onSave">保存</el-button>
    <el-button type="info" size="mini" @click="cancle">取消</el-button>
  </div>
</template>

<script>
import userApi from "@/api/mine/user";
import { Message } from "element-ui";
export default {
  name: "Vue2Index",
  props: ["isShowTree"],
  data() {
    return {
      defaultProps: {
        children: "children",
        label: "name",
      },
      data: [],
      role: {},
      isSelectData: [],
      saveSelectData: [],
    };
  },
  mounted() {},

  methods: {
    // 获取属性节点
    async getTreeData() {
      try {
        let { data } = await userApi.reqTreeList(this.role.id);
        this.data = data.children;
      } catch (error) {
        Message.error(error);
      }
    },
    cancle() {
      this.$bus.$emit("TreeShow", false);
    },
    // 点击树节点的选择
    nodeSelect(node, Select) {
      this.saveSelectData = [...this.$refs.tree.getCheckedNodes()];
    },
    // 获取已选中的id
    isSelectId(data) {
      data.forEach((item) => {
        if (item.children) this.isSelectId(item.children);
        if (item.select && item.type == 2) {
          this.isSelectData.push(item.id);
        }
      });
    },
    async onSave() {
      let saveSelectData = this.saveSelectData.map((item) => item.id);
      try {
        await projectApi.saveTree(this.role.id, saveSelectData);
        Message.success("保存成功");
        this.$bus.$emit("TreeShow", false);
      } catch (error) {
        Message.error(error);
      }
    },
  },
  watch: {
    isShowTree(n) {
      console.log(1);
      if (!n) return;
      this.getTreeData();
    },
    async data(n) {
      if (!n) return;
      this.isSelectId(this.data);
    },
    role() {
      console.log(1);
    },
    isSelectData(n) {},
  },
};
</script>

<style lang="scss" scoped></style>
